<template>
  <div class="">
    <div style="width: 100%; height: 100%; position: relative">
      <div class="myChart" ref="myChart"></div>
      <!-- <div class="zb_space">
        <div class="zb_space_txt_center">
          <div class="lenth">
            <div class="tag" style="background: #4baf02"></div>
            <div>库位总数</div>
            <div class="num">88</div>
          </div>
          <div class="lenth" style="margin: 10px 0">
            <div class="tag" style="background: #eaf112"></div>
            <div>占用总数</div>
            <div class="num">22</div>
          </div>
          <div class="lenth">
            <div class="tag" style="background: #aed80c"></div>
            <div>可用库位数</div>
            <div class="num">58</div>
          </div>
        </div>
      </div> -->
    </div>
  </div>
</template>
<script>
// http://echarts.zhangmuchen.top/#/detail?cid=xT1JWXkiKc
import * as echarts from "echarts";
import { api } from "@/utils/api";

// runSqlAPI
export default {
  name: "Proportion",
  data() {
    return {
      myCharts: null,
      timer: null,
    };
  },
  mounted() {
    this.OptionSet();
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    } else {
      this.timer = setInterval(() => {
        this.OptionSet();
      }, 60 * 60 * 1000); //1h更新一次
    }
  },
  destroyed() {
    clearInterval(this.timer);
    this.timer = null;
  },
  methods: {
    //获取圆上面某点的坐标(x0,y0表示坐标，r半径，angle角度)
    getCirlPoint(x0, y0, r, angle) {
      let x1 = x0 + r * Math.cos((angle * Math.PI) / 180);
      let y1 = y0 + r * Math.sin((angle * Math.PI) / 180);
      return {
        x: x1,
        y: y1,
      };
    },
    getDatesForLastFiveDaysIncludingToday() {
      // 获取当前日期
      const today = new Date();

      // 创建一个数组来存储日期
      const dates = [];

      // 遍历从0（今天）到-4（五天前）的日期
      // for (let i = 0; i <= 4; i++) {
      for (let i = 1; i <= 5; i++) {
        // 设置新的日期为今天减去i天
        const date = new Date(today);
        date.setDate(today.getDate() - i);

        // 将日期添加到数组中（注意：Date对象会被转换为字符串以便存储和显示）
        dates.push(date.toISOString().split("T")[0]); // 如果你只需要日期部分，可以这样格式化
        // 或者，如果你需要完整的Date对象
        // dates.push(date);
      }

      // 返回日期数组
      return dates;
    },
    getDays(days) {
      const sql = `WITH selected_errors AS (
        SELECT 
          EXTRACT(EPOCH FROM (end_time - start_time)) AS error_duration_seconds
        FROM 
          layer1_agv.maintenance_agv_error_log
        WHERE 
          start_time >= '${days} 00:00:00'::timestamp WITH TIME ZONE AND
          end_time <= '${days} 23:59:59'::timestamp WITH TIME ZONE
      )
      SELECT 
        SUM(error_duration_seconds) AS total_error_duration_seconds
      FROM 
        selected_errors;`;
      return sql;
    },
    OptionSet() {
      const lastFiveDays = this.getDatesForLastFiveDaysIncludingToday();
      const test = [];
      lastFiveDays?.forEach((days) => {
        const params = {
          sql: this.getDays(days),
        };
        test.push(api.runSqlAPI(params));
      });
      let value = [15.17, 28.35, 15.36, 58.35, 28.35];
      Promise.all(test).then((res) => {
        let interfaceInfo = res.map((m) => {
          if (m[1] && m[1].data[0]) {
            return !m[1].data[0].total_error_duration_seconds
              ? 0
              : m[1].data[0].total_error_duration_seconds;
          }
        });
        value = interfaceInfo.map((m) => ((m * 100) / (24 * 60 * 60 * 5)).toFixed(2));
        let getData = [];
        lastFiveDays.forEach((item, index) => {
          getData.push({ name: item.slice(5), value: value[index] });
        });
        let myCharts = echarts.init(this.$refs.myChart);
        let xAxisData = [],
          seriesData1 = [],
          sum = 0,
          maxData = [];
        let newObj = [],
          newObj2 = [],
          newObjDat = [];

        let barTopColor = [
          "#2efdfb",
          "#308cff",
          "#23b467",
          "#6c52da",
          "#a05bee",
        ];
        let barBottomColor = [
          "rgba(46,253,251,0.1)",
          "rgba(48, 140, 255, 0.1)",
          "rgba(35, 180, 103, 0.1)",
          "rgba(108, 82, 218, 0.1)",
          "rgba(160, 91, 238, 0.1)",
        ];
        getData.forEach((item, index) => {
          xAxisData.push(item.name);
          seriesData1.push(item.value);
          sum += item.value;
          newObjDat.push("");
          newObjDat[index] = seriesData1[index];
          newObj.push({
            name: item.name,
            value: item.value,
            trueVal: item.value,
            itemStyle: {
              normal: {
                color: "transparent",
                borderColor: barTopColor[index],
                borderType: "dashed",
                borderWidth: 10,
              },
            },
          });
          newObj2.push({
            name: item.name,
            value: item.value,
            trueVal: item.value,
            itemStyle: {
              normal: {
                color: "transparent",
                borderColor: barTopColor[index],
                borderWidth: 50,
              },
            },
          });
        });
        let max = Math.max.apply(null, seriesData1);
        seriesData1.forEach((item) => {
          maxData.push(Number(max) + 10);
        });
        let num = 0;
        let option = {
          title: {
            text: "",
            top: 20,
            left: "center",
            textStyle: {
              color: "#fff",
              fontSize: 20,
            },
          },
          grid: {
            top: "0%",
            left: "5%",
            right: "5%",
            bottom: "5%",
            containLabel: true, //包括文本，居中
          },
          xAxis: {
            data: xAxisData,
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              show: true,
              margin: 25,
              interval: 0,
              align: "center",
              formatter: function (params, index) {
                return "{b|" + params + "}";
              },
              textStyle: {
                fontSize: 14,
                color: "#ffffff",
                rich: {
                  a: {
                    fontSize: 14,
                    color: "#ffffff",
                  },
                  b: {
                    height: 20,
                    fontSize: 14,
                    color: "#ffffff",
                  },
                },
              },
            },
            interval: 0,
          },
          yAxis: {
            splitLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
          },
          series: [
            {
              name: "柱顶部",
              type: "pictorialBar",
              symbolSize: ["40%", 10],
              symbolOffset: [-5, -5],
              z: 12,
              itemStyle: {
                normal: {
                  color: function (params) {
                    return barTopColor[params.dataIndex];
                  },
                },
              },
              label: {
                show: true,
                normal: {
                  show: true,
                  position: "top",
                  color: "#fff",
                  formatter: "{c}%",
                },
                fontSize: 14,
              },
              symbolPosition: "end",
              data: seriesData1,
            },
            {
              name: "柱底部",
              type: "pictorialBar",
              symbolSize: ["40%", 10],
              symbolOffset: [-3, 5],
              z: 12,
              itemStyle: {
                normal: {
                  color: function (params) {
                    return barTopColor[params.dataIndex];
                  },
                },
              },
              data: seriesData1,
            },
            {
              name: "柱顶部",
              type: "pictorialBar",
              symbolSize: ["55%", 10],
              symbolOffset: [-3, -2],
              z: 12,
              itemStyle: {
                normal: {
                  color: function (params) {
                    let clos = barBottomColor[params.dataIndex].split(",");
                    return `${clos[0]},${clos[1]},${clos[2]},0.35)`;
                  },
                },
              },
              label: {
                show: false,
              },
              symbolPosition: "end",
              data: maxData,
            },
            {
              name: "",
              type: "pictorialBar",
              symbolSize: [68, 25],
              symbolOffset: [-4, 20],
              z: 10,
              barMinHeight: 1,
              data: [...newObj],
            },
            {
              name: "",
              type: "pictorialBar",
              symbolSize: [47, 16],
              symbolOffset: [-5, 26],
              z: 10,
              barMinHeight: 1,
              data: [...newObj2],
            },
            {
              type: "bar",
              itemStyle: {
                normal: {
                  color: function (params) {
                    return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 1, color: barTopColor[params.dataIndex] },
                      { offset: 0, color: barBottomColor[params.dataIndex] },
                    ]);
                  },
                  opacity: 0.8,
                },
              },
              z: 18,
              // silent: true,
              barWidth: "35%",
              barGap: "0%",
              data: seriesData1,
            },
            {
              name: "底色",
              type: "bar",
              barWidth: "50%",
              z: 0,
              barGap: "-120%",
              // stack: '',
              symbolPosition: "end",
              itemStyle: {
                normal: {
                  color: function (params) {
                    return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 1, color: barTopColor[params.dataIndex] },
                      { offset: 0, color: barBottomColor[params.dataIndex] },
                    ]);
                  },
                  opacity: 0.3,
                },
              },
              data: maxData,
            },
          ],
        };
        myCharts.setOption(option, true);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@font-face {
  font-family: "FZY4JW";
  src: url("../../assets/font/FZY4JW.TTF");
}
@font-face {
  font-family: "FZZiYHJW";
  src: url("../../assets/font/FZZiYHJW.TTF");
}
.zb_space {
  font-family: "FZY4JW";
  .lenth {
    display: flex;
    justify-content: center;
    align-items: center;
    .num {
      font-size: 28px;
      padding-left: 8px;
      position: relative;
      bottom: 2px;
    }
    span {
      font-size: 28px;
    }
  }
  .tag {
    width: 8px;
    height: 8px;
    background: fuchsia;
    border-radius: 50%;
    margin-right: 5px;
  }
  width: 40%;
  height: 80%;
  //   border: 1px solid rebeccapurple;
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  .zb_space_txt_center {
    // display: flex;
    // justify-content: center;
    // align-items: center;
    // height: 70%;
    // border: 1px solid blue;
  }
}
.myChart,
.myChart2 {
  width: 100%;
  height: 100%;
}
</style>
